package org.zjx.swing.db;
import org.zjx.swing.bean.Font;
import org.zjx.swing.bean.XmlFonts;
import java.util.ArrayList;
import java.util.List;

public class XmlFontsDB {
    private static boolean isTableChecked = false;
    private SQLiteHelper dbHelper;

    public XmlFontsDB() {
        dbHelper = SQLiteHelper.getSingleton();
        // 确保Font表存在（通过FontDB间接初始化）
        if (!isTableChecked) {
            new FontDB(); // 触发Font表创建
            isTableChecked = true;
        }
    }

    // 保存整个XmlFonts数据（覆盖式存储）
    public void save(XmlFonts xmlFonts) {
        // 清空现有数据
        dbHelper.clearData("font");

        // 批量插入新数据
        String sql = "INSERT INTO font (type, name, block, wide, high) VALUES (?, ?, ?, ?, ?)";
        List<Object[]> paramsList = new ArrayList<>();

        for (Font font : xmlFonts.getFonts()) {
            Object[] params = {
                    font.getType(),
                    font.getName(),
                    font.getBlock(),
                    font.getWide(),
                    font.getHigh()
            };
            paramsList.add(params);
        }
        dbHelper.executeBatch(sql, paramsList);
    }

    // 从数据库加载全部数据到XmlFonts对象
    public XmlFonts load() {
        XmlFonts xmlFonts = new XmlFonts();
        String sql = "SELECT * FROM font";
        List<Font> fonts = dbHelper.executeQuery(sql, new Object[0], Font.class);
        xmlFonts.setFonts(fonts);
        return xmlFonts;
    }

    // 清空font表数据
    public void clearData() {
        dbHelper.clearData("font");
    }
}
